import 'package:dio/dio.dart';
import 'package:httpdio/network/api_endpoints.dart';
import 'package:httpdio/service/base_service.dart';
import 'package:httpdio/utils/timestamp_utils.dart';
import '../models/post_model.dart';
import '../models/comment_model.dart';
import '../network/dio_client.dart';

class PostService extends BaseService {
  final Dio _dio = DioClient().dio;
  /// 分页获取帖子
  Future<List<Post>> getPostsPaginated(
      int page,
      int limit, {
        int? userId,
      }) async {
    try {
      final queryParameters = {
        '_page': page,
        '_limit': limit,
        '_sort': 'id',
        '_order': 'desc',
      };

      // 添加用户ID筛选
      if (userId != null) {
        queryParameters['userId'] = userId;
      }

      final response = await _dio.get(
        ApiEndpoints.getPosts,
        queryParameters: queryParameters,
        options: Options(extra: {'logResponse': true}),
      );

      logResponse(response);

      return extractData<List<Post>>(response, (data) {
        return (data as List).map((postJson) => Post.fromJson(postJson)).toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('分页获取帖子错误: $e');
      throw '获取帖子失败';
    }
  }
  Future<List<Post>> getPosts() async {
    try {
      final response = await _dio.get(ApiEndpoints.getPosts);
      final data = response.data as List;
      return data.map((e) => Post.fromJson(e)).toList();
    } on DioException catch (e) {
      throw handleDioError(e);
    }catch (e) {   
      logger.e('获取帖子列表错误: $e');
      throw '获取帖子列表失败';
    }
  }

  Future<Post> getPost(int id) async {
    try {
      final response = await _dio.get(ApiEndpoints.getPost(id));
      return Post.fromJson(response.data);
    } on DioException catch (e) {
      throw handleDioError(e);
    }catch (e) {
      logger.e('获取帖子错误: $e');
      throw '获取帖子失败';
    }
  }
  Future<List<Post>> getPostsByUser(int userId) async {
    try {
      final response = await _dio.get(
        ApiEndpoints.getPosts,
        queryParameters: {'userId': userId},
        options: Options(extra: {'logResponse': true}),
      );

      logResponse(response);

      return extractData<List<Post>>(response, (data) {
        return (data as List).map((postJson) => Post.fromJson(postJson)).toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获取用户帖子列表错误: $e');
      throw '获取用户帖子失败';
    }
  }


  /// 创建新帖子
  Future<Post> createPost(Post post) async {
    try {
      final response = await _dio.post(
        ApiEndpoints.getPosts,
        data: post.toJson(),
        options: Options(
          extra: {'logRequest': true, 'logResponse': true},
        ),
      );

      logResponse(response);

      return extractData<Post>(response, (data) {
        return Post.fromJson(data);
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('创建帖子错误: $e');
      throw '创建帖子失败';
    }
  }

  Future<List<Comment>> getCommentsForPost(int postId) async {
    try {
      final response = await _dio.get(ApiEndpoints.getCommentsForPost(postId));
      final data = response.data as List;
      return data.map((e) => Comment.fromJson(e)).toList();
    } on DioException catch (e) {
      throw handleDioError(e);
    }catch (e) {
      logger.e('获取postId:$postId评论列表错误: $e');
      throw '获取postId:$postId评论列表失败';
    }
  }


  Future<List<Comment>> getAllComments() async {
    try {
      final response = await _dio.get(ApiEndpoints.getComments);
      final data = response.data as List;
      return data.map((e) => Comment.fromJson(e)).toList();
    } on DioException catch (e) {
      throw handleDioError(e);
    }catch (e) {
      logger.e('获取所有评论列表错误: $e');
      throw '获取所有评论列表失败';
    }
  }

  /// 获取今天创建的帖子
  Future<List<Post>> getTodaysPosts() async {
    try {
      final today = TimestampUtils.dateOnly(DateTime.now());
      final tomorrow = today.add(const Duration(days: 1));

      final response = await _dio.get(ApiEndpoints.getPosts, queryParameters: {
        'created_after': TimestampUtils.toJson(today),
        'created_before': TimestampUtils.toJson(tomorrow)
      });
      final data = response.data as List;
      return data.map((e) => Post.fromJson(e)).toList();
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获取今天帖子错误: $e');
      throw '获取今天帖子列表失败';
    }
  }
  /// 获取最近一周的帖子
  Future<List<Post>> getRecentPosts() async {
    try {
      final now = DateTime.now();
      final oneWeekAgo = now.subtract(const Duration(days: 7));

      final response = await _dio.get(
        ApiEndpoints.getPosts,
        queryParameters: {
          'created_after': TimestampUtils.toJson(oneWeekAgo),
        },
      );
      final data = response.data as List;
      return data.map((e) => Post.fromJson(e)).toList();
    }on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获取最近一周的帖子错误: $e');
      throw '获取最近一周的帖子失败';
    }
  }
}
